package com.lzp.java.concurrent.flowcontrol.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author lzp
 * @Description: 多等一，一等多。
 * @date 2021/3/5
 */
public class NAwaitOne2 {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch begin = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(5);
        ExecutorService pool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            final int num = i + 1;
            pool.submit(() -> {
                try {
                    System.out.println("运动员" + num + "准备就绪~");
                    begin.await();
                    System.out.println("运动员" + num + "开始跑步~");
                    TimeUnit.MILLISECONDS.sleep((long) (Math.random() * 1000));
                    System.out.println("运动员" + num + "跑到终点~");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    end.countDown();
                }
            });
        }
        System.out.println("裁判开始准备工作，等待5秒");
        TimeUnit.SECONDS.sleep(5);
        System.out.println("裁判准备完成，开始跑步");
        begin.countDown();
        end.await();
        System.out.println("全部跑步完成");

    }
}
